import { getEnv, getAccountInfoSync, showToast, hideLoading } from '@tarojs/taro';
import { CONTENT_TYPE, ERROR_MSG_DURATION } from '@/constants';
import { useAuthStore } from '@/store';
import { useRouterPush } from '@/composables';
import { localStg, exeStrategyActions } from '@/utils';

const env = getEnv();

/**
 * 获取请求路径
 * @param url
 */
export function getRequestUrl(url: string) {
  let baseUrl = '';
  const actions: Common.StrategyAction[] = [
    [env === 'WEB', () => (baseUrl = `/api${url}`)],
    [
      env === 'WEAPP',
      () => {
        const { miniProgram } = getAccountInfoSync();
        const hosts = {
          develop: 'http://192.168.0.101:8080/jeecg-boot', // 开发
          // develop: 'https://anfine.huasun-healthcare.com/api', // 开发
         //  develop: 'https://603r02036m.goho.co/jeecg-boot', // 开发
         trial: 'http://192.168.0.101:8080/jeecg-boot', // 开发
          // trial: 'https://anfine.huasun-healthcare.com/api', // 体验
          // trial: 'https://603r02036m.goho.co/jeecg-boot', // 开发
          release: 'https://anfine.huasun-healthcare.com/api' // 正式
          // release: 'http://192.168.10.87:8080/jeecg-boot', // 开发
        };
        baseUrl = url.substring(0, 1) === '/' ? `${hosts[miniProgram.envVersion]}${url}` : `${url}`;
      }
    ],
    [
      true,
      () => {
        baseUrl = url.substring(0, 1) === '/' ? `${process.env.HTTP_URL}${url}` : `${url}`;
      }
    ]
  ];
  exeStrategyActions(actions);

  return baseUrl;
}

/** 获取请求头 */
export function getRequestHeaders(axiosConfig: Service.AxiosConfig) {
  const header: TaroGeneral.IAnyObject = {};
  /** 获取token */
  const token = localStg.get('token');
  if (token) {
    /** 添加token */
    // header.Authorization = token;
    header['X-Access-Token'] = token;
  }
  const sys_org_code = localStg.get('sys_org_code') || 'A01';
  if (sys_org_code) {
    header['sys_org_code'] = sys_org_code;
  }
  /** 增加类型 */
  header['Content-Type'] = axiosConfig.contentType || CONTENT_TYPE.json;
  return header;
}

/** token过期处理 */
export function handleExpireToken() {
  console.log('=== Token失效处理开始 ===');
  
  const { resetAuthStore } = useAuthStore();
  const { toLogin } = useRouterPush();
  
  // 隐藏加载状态
  hideLoading();
  
  // 显示提示信息
  showToast({
    title: 'Token失效，请重新登录!',
    icon: 'none',
    duration: 2000
  });
  return
  
  console.log('已显示Token失效提示');
  
  // 清除用户信息
  resetAuthStore();
  console.log('已清除用户信息');
  
  // 延迟跳转到登录页面，让用户看到提示信息
  setTimeout(() => {
    console.log('准备跳转到登录页面');
    toLogin();
  }, 2000);
  
  console.log('=== Token失效处理完成 ===');
  return null;
}

export function showErrorMsg(message: string) {
  hideLoading();

  showToast({
    title: message,
    icon: 'none',
    duration: ERROR_MSG_DURATION
  });
}
